package sse.ustc.cc.custom;

import java.util.List;


import sse.ustc.cc.activity.R;
import sse.ustc.cc.custom.CustomWeekView.OnItemClassClickListener;
import sse.ustc.cc.util.ClassInfo;
import sse.ustc.cc.util.SettingInfo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetricsInt;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.text.StaticLayout;
import android.text.TextPaint;
import android.text.Layout.Alignment;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;

public class CustomWeekViewDoNoeDelete extends View implements OnTouchListener {

	private Paint mPaint; // 画笔,包含了画几何图形、文本等的样式和颜色信息
	private int startX = 0;// 画布的原点X（所有的画图操作，都是基于这个原点的，touch中只要修改这个值）
	private int startY = 0;// 画布的原点Y（所有的画图操作，都是基于这个原点的，touch中只要修改这个值）
	private static final int sidewidte = 60;// 左边，上面bar的宽度
	private static int eachBoxH = 60;// 每个格子的高度
	private static int eachBoxW = 50;// 每个格子的宽度，后面根据屏幕对它做了均分
	private int focusX = -1;// 当前手指焦点的位置坐标
	private int focusY = -1;// 当前手指焦点的位置坐标
	private static int classTotal = 12;// 左边栏总格子数
	private static int dayTotal = 7;// 顶部栏总共格子数
	private String[] weekdays;// 星期
	private boolean isMove = false; // 判断是否移动
	private Context context;
	private boolean isMoved = false;
	private int mLastMotionX, mLastMotionY;
	private static final String TAG = "LongPressView";
	// 长按的runnable
	private Runnable mLongPressRunnable;
	// 移动的阈值
	private static final int TOUCH_SLOP = 2;
	// 监听器
	private OnItemClassClickListener onItemClassClickListener;
	private onItemNoneClassClickListener onItemNoneClassClickListener;

	// 数据
	private List<ClassInfo> classList;
	private List<SettingInfo> settingList;
	private List<SettingInfo> dyweekList;

	// 颜色
	public static final int contentBg = Color.argb(255, 255, 255, 255);
	public static final int barBg = Color.argb(255, 225, 225, 225);
	public static final int bayText = Color.argb(255, 150, 150, 150);
	public static final int barBgHrLine = Color.argb(255, 150, 150, 150);
	public static final int classBorder = Color.argb(180, 150, 150, 150);
	public static final int markerBorder = Color.argb(100, 150, 150, 150);

	// 预设格子背景颜色数组
	public static final int[] classBgColors = { Color.argb(200, 71, 154, 199),
			Color.argb(200, 230, 91, 62), Color.argb(200, 50, 178, 93),
			Color.argb(200, 255, 225, 0), Color.argb(200, 102, 204, 204),
			Color.argb(200, 51, 102, 153), Color.argb(200, 102, 153, 204)

	};

	public CustomWeekViewDoNoeDelete(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.context = context;
		weekdays = context.getResources().getStringArray(R.array.weekdays);
		mPaint = new Paint();
		mLongPressRunnable = new Runnable() {
			@Override
			public void run() {

				Log.i(TAG, "mLongPressRunnable excuted");

				performLongClick(); // 执行长按事件（如果有定义的话）
			}
		};
		setOnTouchListener(this);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		eachBoxW = (getWidth() - sidewidte) / 5;
		
		//printMarker(canvas);
		printContent(canvas);
		printTopBar(canvas);
		printLeftBar(canvas);
		printTopWeek(canvas);
	}

	/**
	 * 顶部周数
	 * 
	 * @param canvas
	 */
	private void printTopWeek(Canvas canvas) {
		
		//Log.e("dyweekList", dyweekList.size()+"");
		if (dyweekList != null && dyweekList.size() > 0) {
			Rect targetRect = new Rect(0, 0, 60, 60);
			Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
			paint.setStrokeWidth(3);
			paint.setTextSize(15);
			String testString = "第"+dyweekList.get(0).getDyweek()+"周";
			paint.setColor(Color.CYAN);
			canvas.drawRect(targetRect, paint);
			paint.setColor(Color.RED);
			FontMetricsInt fontMetrics = paint.getFontMetricsInt();
			int baseline = targetRect.top
					+ (targetRect.bottom - targetRect.top - fontMetrics.bottom + fontMetrics.top)
					/ 2 - fontMetrics.top;
			// 下面这行是实现水平居中，drawText对应改为传入targetRect.centerX()
			paint.setTextAlign(Paint.Align.CENTER);
			canvas.drawText(testString, targetRect.centerX(), baseline, paint);
		}
	}

	
//	private void printContent(Canvas canvas) {
//		// Log.e("classList", classList.size()+"");
//		DisplayMetrics dm = getResources().getDisplayMetrics();// 获取屏幕分辨率
//		eachBoxH = dm.heightPixels / 14 - 1;
//		if (classList != null && classList.size() > 0) {
//			mPaint.setTextSize(20);
//			ClassInfo classInfo;
//			for (int i = 0; i < classList.size(); i++) {
//				classInfo = classList.get(i);
//				int fromX = startX + sidewidte + eachBoxW
//				* (classInfo.getWeekday() - 1);
//		int fromY = startY + sidewidte + eachBoxH
//				* (classInfo.getFromClassNum() - 1);
//		int toX = startX + sidewidte + eachBoxW
//				* classInfo.getWeekday();
//		int toY = startY
//				+ sidewidte
//				+ eachBoxH
//				* (classInfo.getFromClassNum()
//						+ classInfo.getClassNumLen() - 1);
//				classInfo.setPoint(fromX, fromY, toX, toY);
//				// 画classbg
//				mPaint.setStyle(Style.FILL);
//				mPaint.setColor(classBgColors[i % classBgColors.length]);
//				canvas.drawRect(fromX, fromY, toX, toY, mPaint);
//				// 画文字
//				mPaint.setColor(Color.WHITE);
//
//				Rect targetRect = new Rect(fromX, fromY, toX, toY);
//				Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
//				// paint.setStrokeWidth(3);
//				// paint.setTextSize(30);
//				String CourseString = "课程名称：\n" + classInfo.getClassname()
//						+ "\n\n课程教室：\n" + classInfo.getClassRoom()  ;
//
//				// 计算文字所在矩形，可以得到宽高
//				Rect rect = new Rect();
//				paint.getTextBounds(CourseString, 0, CourseString.length(),
//						rect);
//				paint.setColor(Color.CYAN);
//				canvas.drawRect(targetRect, paint);
//				paint.setColor(Color.RED);
//				// 下面这行是实现水平居中，drawText对应改为传入targetRect.centerX()
//				//paint.setTextAlign(Paint.Align.CENTER);
//				TextPaint textPaint = new TextPaint();
//				textPaint.setARGB(0xFF, 255, 0, 0);
//				textPaint.setTextSize(20.0F);
//				textPaint.setAntiAlias(true);
//				StaticLayout layout = new StaticLayout(CourseString, textPaint,
//						targetRect.centerX(), Alignment.ALIGN_NORMAL, 1.0F,
//						0.0F, true);
//				canvas.save();
//				canvas.translate(fromX, fromY);
//				layout.draw(canvas);
//				canvas.restore();
//				// 画边框
//				mPaint.setColor(classBorder);
//				mPaint.setStyle(Style.STROKE);
//				canvas.drawRect(fromX, fromY, toX - 2, toY - 2, mPaint);
//			}
//		}
//	}
	/**
	 * 画中间主体部分
	 * 
	 * @param canvas
	 */
	private void printContent(Canvas canvas) {
		//Log.e("classList", classList.size()+"");
		if (classList != null && classList.size() > 0) {
			mPaint.setTextSize(20);
			ClassInfo classInfo;
			for (int i = 0; i < classList.size(); i++) {
				classInfo = classList.get(i);
				int fromX = startX + sidewidte + eachBoxW
						* (classInfo.getWeekday() - 1);
				int fromY = startY + sidewidte + eachBoxH
						* (classInfo.getFromClassNum() - 1);
				int toX = startX + sidewidte + eachBoxW
						* classInfo.getWeekday();
				int toY = startY
						+ sidewidte
						+ eachBoxH
						* (classInfo.getFromClassNum()
								+ classInfo.getClassNumLen() - 1);
				classInfo.setPoint(fromX, fromY, toX, toY);
				// 画classbg
				mPaint.setStyle(Style.FILL);
				mPaint.setColor(classBgColors[i % classBgColors.length]);
				canvas.drawRect(fromX, fromY, toX - 2, toY - 2, mPaint);
				// 画文字
				mPaint.setColor(Color.WHITE);
//				String className = classInfo.getClassname() 
//						+ classInfo.getClassRoom();
				String className = "名称：    " + classInfo.getClassname()
				+ "  教室： \n" + classInfo.getClassRoom()  ;
				Rect textRect1 = new Rect();
				mPaint.getTextBounds(className, 0, className.length(),
						textRect1);
				int th = textRect1.bottom - textRect1.top;
				int tw = textRect1.right - textRect1.left;
				// 计算行数
				int row = (int) ((tw +50) / eachBoxW +1);
				int length = className.length() / row;
				// 逐行写字
				for (int j = 0; j < row - 1; j++) {
					canvas.drawText(className, length * j, length * (j + 1),
							fromX + 5, fromY + 10 + th * (j + 1), mPaint);
				}
				// 最后一行文字特殊处理
				canvas.drawText(className, length * (row - 1),
						className.length(), fromX + 5, fromY + 10 + th * row,
						mPaint);
				// 画边框
				mPaint.setColor(classBorder);
				mPaint.setStyle(Style.STROKE);
				canvas.drawRect(fromX, fromY, toX - 2, toY - 2, mPaint);
			}
		}
	}

	/**
	 * 画左边课时bar
	 * 
	 * @param canvas
	 */
	private void printLeftBar(Canvas canvas) {
//		// =================画左边课时栏=================
//		mPaint.setColor(barBg);
//		mPaint.setStyle(Style.FILL);
//		mPaint.setTextSize(30);
//		// 课时栏背景
//		canvas.drawRect(0, startY + sidewidte, sidewidte, sidewidte + startY
//				+ eachBoxH * classTotal, mPaint);
//		mPaint.setColor(barBgHrLine);
//		// 画第一个边框线
//		canvas.drawRect(0, startY + sidewidte + eachBoxH - 1, sidewidte, startY
//				+ eachBoxH + sidewidte, mPaint);
//		// 居中处理
//		Rect textRect1 = new Rect();
//		mPaint.getTextBounds("1", 0, 1, textRect1);
//		int th = textRect1.bottom - textRect1.top;
//		int tw1 = textRect1.right - textRect1.left;
//		mPaint.getTextBounds("10", 0, 2, textRect1);
//		int tw2 = textRect1.right - textRect1.left;
//		// 画第一个文字
//		canvas.drawText("1", sidewidte / 2 - tw1, startY + sidewidte + eachBoxH
//				/ 2 + th / 2, mPaint);
//		for (int i = 2; i < classTotal + 1; i++) {
//			// 画边框
//			canvas.drawRect(0, startY + sidewidte + eachBoxH * i - 1,
//					sidewidte, startY + eachBoxH * i + sidewidte, mPaint);
//			// 画文字
//			int tw = tw1 * 2 + (tw2 - tw1) * (i / 10);
//			canvas.drawText(i + "", sidewidte / 2 - tw / 2, startY + sidewidte
//					+ eachBoxH * (i - 1) + eachBoxH / 2 + th / 2, mPaint);
//		}
//		// =========左上角正方形============
//		canvas.drawRect(0, 0, sidewidte, sidewidte, mPaint);
		// =================画左边课时栏=================
				DisplayMetrics dm = getResources().getDisplayMetrics();// 获取屏幕分辨率
				eachBoxH = dm.heightPixels / 14 - 1;
				//Log.e("eachBoxH", eachBoxH + " " + dm.heightPixels + "");
				mPaint.setColor(barBg);
				mPaint.setStyle(Style.FILL);
				mPaint.setTextSize(30);
				// 课时栏背景
				canvas.drawRect(0, startY + sidewidte, sidewidte, sidewidte + startY
						+ eachBoxH, mPaint);
				mPaint.setColor(barBgHrLine);
				// 画第一个边框线
				canvas.drawRect(0, startY + sidewidte + eachBoxH - 1, sidewidte, startY
						+ eachBoxH + sidewidte, mPaint);
				// 居中处理
				Rect textRect1 = new Rect();
				mPaint.getTextBounds("1", 0, 1, textRect1);
				int th = textRect1.bottom - textRect1.top;
				int tw1 = textRect1.right - textRect1.left;
				mPaint.getTextBounds("10", 0, 2, textRect1);
				int tw2 = textRect1.right - textRect1.left;
				// 画第一个文字
				canvas.drawText("1", sidewidte / 2 - tw1, startY + sidewidte + eachBoxH
						/ 2 + th / 2, mPaint);
				for (int i = 2; i < 14; i++) {
					// 画边框
					canvas.drawRect(0, startY + sidewidte + eachBoxH * i - 1,
							sidewidte, startY + eachBoxH * i + sidewidte, mPaint);
					// 画文字
					int tw = tw1 * 2 + (tw2 - tw1) * (i / 10);
					canvas.drawText(i + "", sidewidte / 2 - tw / 2, startY + sidewidte
							+ eachBoxH * (i - 1) + eachBoxH / 2 + th / 2, mPaint);
				}
				// =========左上角正方形============
				canvas.drawRect(0, 0, sidewidte, sidewidte, mPaint);
	}

	/**
	 * 画顶部星期bar
	 * 
	 * @param canvas
	 */
	private void printTopBar(Canvas canvas) {
		// =================画顶部星期栏==================
		mPaint.setColor(barBg);
		mPaint.setStyle(Style.FILL);
		// 星期栏背景
		canvas.drawRect(startX + sidewidte, 0, sidewidte + startX + eachBoxW
				* dayTotal, sidewidte, mPaint);
		mPaint.setColor(barBgHrLine);
		// 画第一个边框线
		mPaint.setTextSize(25);
		canvas.drawRect(startX + sidewidte + eachBoxW - 1, 0, startX + eachBoxW
				+ sidewidte, sidewidte, mPaint);
		// 居中处理
		Rect textBounds = new Rect();
		mPaint.getTextBounds(weekdays[0], 0, weekdays[0].length(), textBounds);
		int textHeight = textBounds.bottom - textBounds.top;
		int textWidth = textBounds.right - textBounds.left;
		// 画第一个文字
		canvas.drawText(weekdays[0], startX + sidewidte + eachBoxW / 2
				- textWidth / 2, sidewidte / 2 + textHeight / 2, mPaint);
		for (int i = 2; i < dayTotal + 1; i++) {
			// 画边框线
			canvas.drawRect(startX + sidewidte + eachBoxW * i - 1, 0, startX
					+ eachBoxW * i + sidewidte, sidewidte, mPaint);
			// 画文字
			canvas.drawText(weekdays[i - 1], startX + sidewidte + eachBoxW
					* (i - 1) + eachBoxW / 2 - textWidth / 2, sidewidte / 2
					+ textHeight / 2, mPaint);
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			focusX = (int) event.getX();
			focusY = (int) event.getY();
			isMove = false;

		} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
			int dx = (int) (event.getX() - focusX);
			int dy = (int) (event.getY() - focusY);
			if (!isMove && Math.abs(dx) < 5 && Math.abs(dy) < 5) {
				isMove = false;
				return false;
			}
			isMove = true;
			// 判断是否超出左右边框
			if (startX + dx < 0
					&& startX + dx + eachBoxW * dayTotal + sidewidte >= getWidth()) {
				startX += dx;
			}
			// 判断是否超出上下边框
			if (startY + dy < 0
					&& startY + dy + eachBoxH * classTotal + sidewidte >= getHeight()) {
				startY += dy;
			}
			// 重新获得焦点坐标
			focusX = (int) event.getX();
			focusY = (int) event.getY();
			// 重绘
			invalidate();
		} else if (event.getAction() == MotionEvent.ACTION_UP) {
			if (!isMove) {
				int focusX = (int) event.getX();
				int focusY = (int) event.getY();
				// 是点击效果，遍历是哪个课程的点击效果
				for (int i = 0; i < classList.size(); i++) {
					ClassInfo classInfo = classList.get(i);
					if (focusX > classInfo.getFromX()
							&& focusX < classInfo.getToX()
							&& focusY > classInfo.getFromY()
							&& focusY < classInfo.getToY()) {
						if (onItemClassClickListener != null) {
							onItemClassClickListener.onClick(classInfo);
						}
						break;
					}

				}
			}
		}
		return true;
	}

//	public boolean dispatchTouchEvent(MotionEvent event) {
//		int x = (int) event.getX();
//		int y = (int) event.getY();
//
//		switch (event.getAction()) {
//		case MotionEvent.ACTION_DOWN:
//
//			mLastMotionX = x;
//			mLastMotionY = y;
//			isMoved = false;
//
//			/*
//			 * 将mLongPressRunnable放进任务队列中，到达设定时间后开始执行 这里的长按时间采用系统标准长按时间
//			 */
//			postDelayed(mLongPressRunnable,
//					ViewConfiguration.getLongPressTimeout());
//			break;
//		case MotionEvent.ACTION_MOVE:
//			int dx = (int) (event.getX() - focusX);
//			int dy = (int) (event.getY() - focusY);
//			if (!isMoved && Math.abs(dx) < 5 && Math.abs(dy) < 5) {
//				isMoved = false;
//				return false;
//			}
//
//			Log.e("move：x:y:", dx + "" + dy + "");
//			float one,two;
//			one =startX + dx;
//			two=startX + dx + eachBoxW * dayTotal + sidewidte ;
//			Log.e("tartX + dx:", one + " "+getWidth());
//			Log.e("startX + dx + eachBoxW * dayTotal + sidewidte:",two+ " "+getWidth());
//			isMoved = true;
//			// 判断是否超出左右边框
//			if (startX + dx < 0
//					&& startX + dx + eachBoxW * dayTotal + sidewidte >= getWidth()) {
//				startX += dx;
//			}
//			// 判断是否超出上下边框
//			if (startY + dy < 0
//					&& startY + dy + eachBoxH * classTotal + sidewidte >= getHeight()) {
//				startY += dy;
//			}
//			// 重新获得焦点坐标
//			focusX = (int) event.getX();
//			focusY = (int) event.getY();
//			// 重绘
//			invalidate();
//
//			removeCallbacks(mLongPressRunnable);
//			break;
//		case MotionEvent.ACTION_UP:
//			// 释放了
//			int n = 0;
//			Log.e("IsMoved", isMoved + "");
//			if (!isMoved) {
//				removeCallbacks(mLongPressRunnable);
//				int focusX = (int) event.getX();
//				int focusY = (int) event.getY();
//
//				Log.e("up：x:y:", focusX + "" + focusY + "");
//				// Log.e("moveflow：x:y:",flowdx+""+flowdy+"");
//				// 是点击效果，遍历是哪个课程的点击效果
//				for (int i = 0; i < classList.size(); i++) {
//					Log.e("size", classList.size() + "");
//					ClassInfo classInfo = classList.get(i);
//					Log.e("123：x:y:",
//							classInfo.getFromX() + "" + classInfo.getFromY()
//									+ "");
//					Log.e("456：x:y:",
//							classInfo.getFromY() + "" + classInfo.getToY() + "");
//					if (focusX > classInfo.getFromX()
//							&& focusX < classInfo.getToX()
//							&& focusY > classInfo.getFromY()
//							&& focusY < classInfo.getToY()) {
//						if (onItemClassClickListener != null) {
//							n = 0;
//							onItemClassClickListener.onClick(classInfo);
//						} else {
//							// onItemNoneClassClickListener.onClick();
//						}
//						break;
//					} else {
//						n++;
//						// onItemNoneClassClickListener.onClick();
//						// break;
//					}
//				}
//				if (n != 0) {
//					onItemNoneClassClickListener.onClick();
//				}
//
//			}
//			removeCallbacks(mLongPressRunnable);
//			break;
//		}
//
//		return true;
//	}

	@Override
	public boolean onKeyLongPress(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		super.onKeyLongPress(keyCode, event);
		System.out.println();
		return true;
	}

	public interface OnItemClassClickListener {
		// 单击事件
		public void onClick(ClassInfo classInfo);

	}

	public OnItemClassClickListener getOnItemClassClickListener() {
		return onItemClassClickListener;
	}

	public void setOnItemClassClickListener(
			OnItemClassClickListener onItemClassClickListener) {
		this.onItemClassClickListener = onItemClassClickListener;
	}

	public interface onItemNoneClassClickListener {
		public void onClick();

	}

	public onItemNoneClassClickListener getonItemNoneClassClickListener() {
		return onItemNoneClassClickListener;
	}

	public void setonItemNoneClassClickListener(
			onItemNoneClassClickListener onItemNoneClassClickListener) {
		this.onItemNoneClassClickListener = onItemNoneClassClickListener;
	}

	public List<ClassInfo> getClassList() {
		return classList;
	}

	public void setClassList(List<ClassInfo> classList) {
		this.classList = classList;
		invalidate();// 刷新页面
	}

	public List<SettingInfo> getSettingList() {
		return settingList;
	}

	public void setSettingList(List<SettingInfo> settingList) {
		this.settingList = settingList;
		invalidate();// 刷新页面
	}

	public List<SettingInfo> getDyweekList() {
		return dyweekList;
	}

	public void setDyweekList(List<SettingInfo> dyweekList) {
		this.dyweekList = dyweekList;
		invalidate();// 刷新页面
	}

	
}
